package com.yyx.service.impl;

import com.yyx.exception.BusinessException;
import com.yyx.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Override
    public String upload(MultipartFile file) throws IOException {
        return upload(file, uploadDir);
    }

    @Override
    public String upload(MultipartFile file, String position) throws IOException {
        validateFile(file);

        String uniqueFileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
        Path filePath = prepareUploadDir(position).resolve(uniqueFileName);

        file.transferTo(filePath.toFile());
        return uniqueFileName;
    }

    @Override
    public void delete(String fileUrl) {
        if (fileUrl != null && !fileUrl.isEmpty()) {
            File file = new File(uploadDir + fileUrl);
            if (file.exists()) {
                file.delete();
            }
        }
    }

    private void validateFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new BusinessException("上传文件不能为空");
        }
    }

    private Path prepareUploadDir(String uploadDir) throws IOException {
        File directory = new File(uploadDir);
        if (!directory.exists() && !directory.mkdirs()) {
            throw new BusinessException("无法创建上传目录: " + uploadDir);
        }
        return directory.toPath();
    }
}